import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { debounce } from 'lodash-es'
import { houseApi } from '../api/houseApi'

export const useHouseStore = defineStore('house', {
  state: () => ({
    houses: [],
    totalHouses: 0,
    cities: [],
    loading: false,
    currentHouse: null,
    // 搜索和筛选状态
    currentCity: '',
    searchQuery: '',
    filters: {
      priceRange: [0, 1000],
      areaRange: [0, 200],
      layout: '',
      decoration: ''
    },
    sortOption: 'default', // 排序选项: default, priceAsc, priceDesc, areaAsc, areaDesc
    currentPage: 1,
    pageSize: 10
  }),
  
  actions: {
    // 获取城市列表
    async fetchCities() {
      try {
        this.loading = true
        this.cities = await houseApi.getCities()
        return this.cities
      } catch (error) {
        console.error('获取城市列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 搜索房源
    async searchHouses(params) {
      try {
        this.loading = true
        const result = await houseApi.searchHouses(params)
        this.houses = result.content
        this.totalHouses = result.totalElements
        return {
          houses: this.houses,
          total: this.totalHouses
        }
      } catch (error) {
        console.error('搜索房源失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取房源详情
    async getHouseDetail(id) {
      try {
        this.loading = true
        this.currentHouse = await houseApi.getHouseDetail(id)
        return this.currentHouse
      } catch (error) {
        console.error('获取房源详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取推荐房源
    async getRecommendHouses(id) {
      try {
        this.loading = true
        const result = await houseApi.getRecommendHouses(id)
        return result
      } catch (error) {
        console.error('获取推荐房源失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取筛选选项
    async fetchFilterOptions() {
      try {
        this.loading = true
        const result = await houseApi.getFilterOptions()
        return result
      } catch (error) {
        console.error('获取筛选选项失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取房源对比数据
    async compareHouses(ids) {
      try {
        this.loading = true
        const result = await houseApi.compareHouses(ids)
        return result
      } catch (error) {
        console.error('获取房源对比数据失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 设置搜索查询
    setSearchQuery(query) {
      this.searchQuery = query;
    },

    // 设置当前城市
    setCity(city) {
      this.currentCity = city;
    },

    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
    },
    
    // 设置排序选项
    setSort(sortOption) {
      this.sortOption = sortOption;
    },
    
    // 设置页码
    setPage(page) {
      this.currentPage = page;
    },
    
    // 设置每页条数
    setPageSize(size) {
      this.pageSize = size;
    },

    // 应用筛选条件并搜索
    async applyFilters() {
      // 构建查询参数
      const params = {};
      
      // 只添加有效的参数
      if (this.currentCity) {
        params.city = this.currentCity;
      }
      
      // 价格区间处理
      if (this.filters.priceRange && 
          (this.filters.priceRange[0] > 0 || this.filters.priceRange[1] < 1000)) {
        params.priceRange = `${this.filters.priceRange[0]}-${this.filters.priceRange[1]}万`;
      }
      
      // 面积区间处理
      if (this.filters.areaRange && 
          (this.filters.areaRange[0] > 0 || this.filters.areaRange[1] < 200)) {
        params.areaRange = `${this.filters.areaRange[0]}-${this.filters.areaRange[1]}㎡`;
      }
      
      // 户型处理
      if (this.filters.layout && this.filters.layout !== '') {
        params.layout = this.filters.layout;
        console.log('添加户型查询参数:', this.filters.layout);
        console.log('发送到后端的户型查询参数类型:', typeof this.filters.layout);
      }
      
      // 装修处理
      if (this.filters.decoration && this.filters.decoration !== '') {
        params.decoration = this.filters.decoration;
      }
      
      // 搜索关键词处理
      if (this.searchQuery && this.searchQuery.trim()) {
        params.query = this.searchQuery.trim();
      }
      
      // 排序处理
      if (this.sortOption && this.sortOption !== 'default') {
        params.sort = this.sortOption;
      }
      
      // 分页参数
      params.page = this.currentPage - 1; // 后端分页从0开始
      params.size = this.pageSize;
      
      console.log('搜索参数:', params);
      
      return this.searchHouses(params);
    },

    // 获取房源列表（用于分页或初始加载）
    async fetchHouses() {
      return this.applyFilters();
    }
  }
}) 